package cn.com.longfuinfo.wx.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.jfinal.kit.PropKit;
import com.jfinal.log.Logger;
import com.jfinal.weixin.sdk.api.AccessTokenApi;

import cn.com.longfuinfo.api.api.UserAPI;
import cn.com.longfuinfo.api.bean.EventMessage;
import cn.com.longfuinfo.api.bean.User;
import cn.com.longfuinfo.api.bean.xmlmessage.XMLMessage;
import cn.com.longfuinfo.api.bean.xmlmessage.XMLNewsMessage;
import cn.com.longfuinfo.api.bean.xmlmessage.XMLNewsMessage.Article;
import cn.com.longfuinfo.api.bean.xmlmessage.XMLTextMessage;
import cn.com.longfuinfo.wx.controller.BaseController;
import cn.com.longfuinfo.wx.controller.SystemController;
import cn.com.longfuinfo.wx.dao.WxUser;
import cn.com.longfuinfo.wx.exception.SaveException;
import cn.com.longfuinfo.wx.exception.ServiceLocatorException;
import cn.com.longfuinfo.wx.kit.DatetimeKit;

public class WxEventControlService {
	
	private Logger log = Logger.getLogger(this.getClass());
	private UserAPI userApi;
	private UserService userService = new UserService();
	SystemController sc=new SystemController();
	BaseController bc=new BaseController();

	/**
	 * 用户订阅
	 */
	public XMLMessage subscribe(EventMessage eventMessage) throws SaveException {
		log.debug("用户订阅====01===>");
		XMLMessage xmlMessage;
		try {
			String returnMesssage = PropKit.get("wx.default_msg1");
			String openid = eventMessage.getFromUserName();//用户的标识，对当前公众号唯一
			if(openid==null){
				returnMesssage = PropKit.get("wx.no_attention");
			}else{
				
				//通过微信用户的openid 得到用户的信息 ，用于保存到本地服务器重
				userApi = new UserAPI(); 
				String access_token = AccessTokenApi.getAccessTokenStr();
				User user = userApi.userInfo(access_token,openid);
				String errorcode = user.getErrcode();
				if(errorcode == null  || errorcode.equals("0")){//查询用户出现错误
				}else{
					returnMesssage = user.getErrmsg()==null ? "温馨提示:得到用户信息出现错误!请重新关注" : user.getErrmsg();
					xmlMessage = new XMLTextMessage(eventMessage.getFromUserName(),eventMessage.getToUserName() ,returnMesssage);
					return xmlMessage;
				}
				//是否关注 没有关注该公众号，拉取不到其余信息
				int SUBSCRIBE = user.getSubscribe();
				if(SUBSCRIBE==0){
					returnMesssage = PropKit.get("wx.no_attention");
				}else{
				
					//判断此用户是否在系统中存在
					WxUser wxUser= userService.findByOpenid(openid);
					//存在这个用户,不进行保存 并进行修改用户信息  否则,系统中添加一条用户信息
					if(wxUser != null){
						wxUser.set("nickname", user.getNickname().replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "LF"))
							  .set("headimgurl", user.getHeadimgurl())
						  	  .set("openid", user.getOpenid())
						  	  .set("sex", user.getSex())
						  	  .set("subscribe", 1)
						  	  .set("city", user.getCity().replaceAll("[\\x{10000}-\\x{10FFFF}]", ""))
						  	  .set("country", user.getCountry().replaceAll("[\\x{10000}-\\x{10FFFF}]", ""))
						  	  .set("province", user.getProvince().replaceAll("[\\x{10000}-\\x{10FFFF}]", ""))
						  	  .set("unionid", user.getUnionid())
						  	  .set("updateDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).update();
						   int userid=wxUser.getInt("userid");
							if(userid >0){
								cn.com.longfuinfo.wx.dao.User record=userService.findByUser(userid);
								record.set("guanzhu", 2).update();
							}
						returnMesssage ="您好"+wxUser.getStr("nickname");
					}else{
						wxUser = new WxUser();
						wxUser.set("nickname", user.getNickname().replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "LF"))
							  .set("headimgurl", user.getHeadimgurl())
							  .set("openid", user.getOpenid())
							  .set("sex", user.getSex())
							  .set("subscribe", 1)
							  .set("city", user.getCity().replaceAll("[\\x{10000}-\\x{10FFFF}]", ""))
							  .set("country", user.getCountry().replaceAll("[\\x{10000}-\\x{10FFFF}]", ""))
							  .set("province", user.getProvince().replaceAll("[\\x{10000}-\\x{10FFFF}]", ""))
							  .set("unionid", user.getUnionid())
							  .set("updateDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).save();
						wxUser = userService.findByOpenid(openid);
						 int userid=wxUser.getInt("userid");
							if(userid >0){
								cn.com.longfuinfo.wx.dao.User record=userService.findByUser(userid);
								record.set("guanzhu", 2).update();
							}
						returnMesssage ="您好"+wxUser.getStr("nickname");
					}
				}
			}
			
			//创建回复
			xmlMessage = new XMLTextMessage(eventMessage.getFromUserName(),eventMessage.getToUserName() ,returnMesssage);
			
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			throw new ServiceLocatorException(e.getMessage(), e);
		}
		return xmlMessage;
	}
	
	/**
	 * 微信用户取消订阅
	 */
	public XMLMessage unsubscribe(EventMessage eventMessage) throws SaveException{
		log.info("微信用户取消订阅01");
		XMLMessage xmlMessage;
		try {
			String returnMesssage = PropKit.get("wx.default_msg");
			String openid = eventMessage.getFromUserName();//用户的标识，对当前公众号唯一
			if(openid==null){
				returnMesssage = PropKit.get("wx.no_attention");
			}else{
				//判断此用户是否在系统中存在
				WxUser wxUser= userService.findByOpenid(openid);
				
				//存在这个用户,修改用户信息为未订阅
				if(wxUser != null){
					wxUser.set("subscribe", "0").update();
					 int userid=wxUser.getInt("userid");
						if(userid >0){
							cn.com.longfuinfo.wx.dao.User record=userService.findByUser(userid);
							record.set("guanzhu", 1).update();
						}
				}
			}
			log.debug(returnMesssage);
			
			//创建回复
			xmlMessage = new XMLTextMessage(eventMessage.getFromUserName(),eventMessage.getToUserName() ,returnMesssage);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			throw new ServiceLocatorException(e.getMessage(), e);
		}
		return xmlMessage;
	}
	/**
	 * 关注微信扫码
	 * @param eventMessage
	 * @return
	 */
	public XMLMessage qrcodeScan(EventMessage eventMessage)throws SaveException {
		XMLNewsMessage xmlMessage;
		try {
			log.info("关注======0003===>");
			//保存或修改用户微信信息
			updateWxUser(eventMessage);
			
			String vid=eventMessage.getEventKey();
			String longfu="";
			String openid = eventMessage.getFromUserName();//用户的标识，对当前公众号唯一
			if (StringUtils.isEmpty(vid) || vid.indexOf("_") == -1) {

		         xmlMessage =null;
			}else {
				longfu=vid.substring(0,vid.indexOf("_"));
				if(longfu.equals("longfu")){
					List<Article> list = new ArrayList<Article>();
					Article article = new Article();  
		            article.setTitle("会员注册");  
		            article.setDescription("点击绑定导购员");  
		            article.setPicurl("http://47.92.148.151:8084/tuwen.png");  
		            article.setUrl("http://shop.bain.net.cn/regist/"+vid.substring(vid.indexOf("_")+1,vid.length())); 
		            log.info("id-----longfu0-------"+vid);
		            list.add(article); 
					xmlMessage = new XMLNewsMessage(eventMessage.getFromUserName(),eventMessage.getToUserName(),list);
				}else{

			         xmlMessage =null;
				}
			}
			 
			
			
			
		} catch (Exception e){
			e.printStackTrace();
			log.error(e.getMessage());
			throw new ServiceLocatorException(e.getMessage(), e);
		}
		return xmlMessage;
	}
	/**
	 * 未关注关注微信扫码
	 * @param eventMessage
	 * @return
	 */
	public XMLNewsMessage subscribes(EventMessage eventMessage) throws SaveException {
		log.info("用户扫码订阅======02===>");
		XMLNewsMessage xmlMessage = null;
//		XMLMessage xmltextMessage=null;
		try {

				//保存或修改用户微信信息
				updateWxUser(eventMessage);
				String eventKeyStr=eventMessage.getEventKey();

					if (StringUtils.isEmpty(eventKeyStr) || eventKeyStr.indexOf("_") == -1) {
						xmlMessage = null;
					}else {
						String qrscene = eventKeyStr.substring(eventKeyStr.indexOf("_")+1,eventKeyStr.length());
						log.info("1111========>--qrscene----"+qrscene);
						if (StringUtils.isEmpty(qrscene) || qrscene.indexOf("_") == -1) {
							xmlMessage = null;
						}else {
							String longfu="";
							log.info("id-----1111---qrscene----"+qrscene);
							longfu=qrscene.substring(0,qrscene.indexOf("_"));
							if(!StringUtils.isEmpty(longfu) && "longfu".equals(longfu)){
								List<Article> list = new ArrayList<Article>();
								Article article = new Article();  
					            article.setTitle("会员注册");  
					            article.setDescription("点击绑定导购员");  
					            article.setPicurl("http://47.92.148.151:8084/tuwen.png");  
					            //這裡得到是 == longfu_237 将无法注册  新的二维码
					            article.setUrl("http://shop.bain.net.cn/regist/"+qrscene.substring(qrscene.indexOf("_")+1,qrscene.length())); 
					            log.info("3333========>-----longfu1--"+qrscene.substring(qrscene.indexOf("_")+1,qrscene.length()));
					            list.add(article); 
								xmlMessage = new XMLNewsMessage(eventMessage.getFromUserName(),eventMessage.getToUserName(),list);
							}else{

								xmlMessage = null;
							}
						}
						log.info("id-----33333---结束----");
					
					}
				
			
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			throw new ServiceLocatorException(e.getMessage(), e);
		}
		return xmlMessage;
	}
	
	/**
	 * 用户关注公众号时保存或修改用户微信信息
	 * @param eventMessage
	 */
	public void updateWxUser(EventMessage eventMessage) {
		//判断此用户是否在系统中存在
		String openid = eventMessage.getFromUserName();//用户的标识，对当前公众号唯一
		log.info("用户的标识，对当前公众号唯一===openid===>"+openid);
		if(openid==null){
			log.info("没有关注00===>");
		}else{
			
			//存在这个用户,不进行保存 并进行修改用户信息  否则,系统中添加一条用户信息
			//判断此用户是否在系统中存在
			userApi = new UserAPI(); 
			String access_token = AccessTokenApi.getAccessTokenStr();
			log.info("关注000====access_token===>"+access_token);
			User user = userApi.userInfo(access_token,openid);
			
			log.info("关注000====user===>"+user);
			WxUser wxUser= userService.findByOpenid(openid);
			log.info("关注111===wxUser===>"+wxUser);
				//存在这个用户,不进行保存 并进行修改用户信息  否则,系统中添加一条用户信息
			if(wxUser != null){
				//通过微信用户的openid 得到用户的信息 ，用于保存到本地服务器重
				if (access_token!=null && user!=null) {
					wxUser.set("nickname", user.getNickname().replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "LF"))
					  .set("headimgurl", user.getHeadimgurl())
				  	  .set("openid", user.getOpenid())
				  	  .set("sex", user.getSex())
				  	  .set("subscribe", 1)
				  	  .set("city", user.getCity().replaceAll("[\\x{10000}-\\x{10FFFF}]", ""))
				  	  .set("country", user.getCountry().replaceAll("[\\x{10000}-\\x{10FFFF}]", ""))
				  	  .set("province", user.getProvince().replaceAll("[\\x{10000}-\\x{10FFFF}]", ""))
				  	  .set("unionid", user.getUnionid())
				  	  .set("updateDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).update();
				   int userid=wxUser.getInt("userid");
					if(userid >0){
						cn.com.longfuinfo.wx.dao.User record=userService.findByUser(userid);
						//修改用户是否关注公众号状态
						record.set("guanzhu", 2).update();
					}else{
						//当前微信号没有关联手机用户
						log.info("当前微信号没有关联手机账号===>");
					}
				}else{
					log.info("当前微信号access_token无法获取===>"+access_token);
				}
				
			}else{
				wxUser = new WxUser();
				String eventKey=eventMessage.getEventKey();
				//通过微信用户的openid 得到用户的信息 ，用于保存到本地服务器重
				if (access_token!=null && user!=null) {
					wxUser.set("nickname", user.getNickname().replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "LF"))
					  .set("headimgurl", user.getHeadimgurl())
				  	  .set("openid", openid)
				  	  .set("sex", user.getSex())
				  	  .set("subscribe", 1)
				  	  .set("city", user.getCity().replaceAll("[\\x{10000}-\\x{10FFFF}]", ""))
				  	  .set("country", user.getCountry().replaceAll("[\\x{10000}-\\x{10FFFF}]", ""))
				  	  .set("province", user.getProvince().replaceAll("[\\x{10000}-\\x{10FFFF}]", ""))
				  	  .set("unionid", user.getUnionid())
				  	  .set("updateDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).save();
					
					WxUser wxUsernew = userService.findByOpenid(openid);
				
					//保存导购id
					updateDaoGUid(eventKey,wxUsernew);
			
				}else{
					log.info("当前微信号access_token无法获取===>"+access_token);
					//只保存openid
					wxUser.set("openid", openid).save();
					WxUser wxNewUser = userService.findByOpenid(openid);
					//保存导购id
					updateDaoGUid(eventKey,wxNewUser);
				}
			}
			
		}
	}
	
	/**
	 * 在扫码关注时，保存导购id
	 * @param eventKey
	 * @param mWxUser
	 */
	public void updateDaoGUid(String eventKey,WxUser mWxUser) {
		String longfu="";
		log.info("新用户扫码关注，保存导购的ID=======kkk====================>"+eventKey);
		if (StringUtils.isEmpty(eventKey) || eventKey.indexOf("_") == -1) {
	         log.info("新用户扫码关注，保存导购的ID=================================>"+eventKey);
		}else {
			String longfuNew = eventKey.substring(0,eventKey.indexOf("_"));
			String qrscene = eventKey.substring(eventKey.indexOf("_")+1,eventKey.length());
			
			if(!StringUtils.isEmpty(longfuNew) && "longfu".equals(longfuNew)){
				String daogUserId = qrscene;
				//保存
				mWxUser.set("daogouUid", daogUserId).update();
	            log.info("新用户扫码关注，保存导购的ID=======longfuNew==============>"+daogUserId);
	        
			}else{
				
				 log.info("新用户扫码关注，保存导购的ID============000======截取longfu专用字符串===============>"+qrscene);
				if (StringUtils.isEmpty(qrscene) || qrscene.indexOf("_") == -1) {
					log.info("新用户扫码关注，保存导购的ID=============111=====截取longfu专用字符串为null===============>"+qrscene);
				}else {
					 log.info("新用户扫码关注，保存导购的ID===========2222=======截取longfu专用字符串===============>"+qrscene);
					longfu=qrscene.substring(0,qrscene.indexOf("_"));
					if(!StringUtils.isEmpty(longfu) && "longfu".equals(longfu)){
						String daogUserId = qrscene.substring(qrscene.indexOf("_")+1,qrscene.length());
						//保存
						mWxUser.set("daogouUid", daogUserId).update();
			            log.info("新用户扫码关注，保存导购的ID==========333========截取longfu专用用户id===============>"+daogUserId);
			        
					}else{
						log.info("新用户扫码关注，保存导购的ID=========没有截取到longfu字符串=======失败=========>");
					}
				}
			}
		
			log.info("======================>---结束----");
		
		}
	}
}
